/**
 * Created by oneminute on 8/4/14.
 */

var lz = require("../lib/utils/modules")();
var nodemailer = require('nodemailer');
var request = require("request");
var xmlParser = require("xml2json");
var util = require("util");

exports.post = function (_req, _res, _opts, _callback) {
    var email = _opts.email;
    var name = _opts.name;
    var loginPhone = _opts.loginPhone;

    if (email) {
        var user = new lz.User();
        user.load({
            method: "byAQL",
            aql: lz.Config.db.arango.aqls.GET_USER_BY_EMAIL,
            params: {
                "@users": lz.Config.db.arango.users,
                "@emails": lz.Config.db.arango.emails,
                "email": email
            }
        }, function (_err, _user) {
            if (_err) {
                lz.Logger.error("/findpassword: 按email查找用户出现错误。", name);
                _callback(_err, _opts.user);
                return;
            }

            if (_user) {
                sendMail(_user.email.email, _user.password);
                return;
            } else {
                _callback(lz.Config.errors.getError(lz.Config.errors.LOGIN_USER_NOT_FOUND));
                return;
            }
        });
        return;
    } else if (name) {
        var user = new lz.User();
        user.load({
            method: "byProp",
            prop: "name",
            value: name
        }, function (_err, _user) {
            if (_err) {
                lz.Logger.error("/findpassword: 按name查找用户出现错误。", name);
                _callback(_err, _opts.user);
                return;
            }

            if (_user) {
                sendMail(_user.email.email, _user.password);
                return;
            } else {
                _callback(lz.Config.errors.getError(lz.Config.errors.LOGIN_USER_NOT_FOUND));
                return;
            }
        });
    } else if (loginPhone) {
        var user = new lz.User();
        user.load({
            method: "byProp",
            prop: "loginPhone",
            value: loginPhone
        }, function (_err, _user) {
            if (_err) {
                lz.Logger.error("/findpassword: 按loginPhone查找用户出现错误。", name);
                _callback(_err, _opts.user);
                return;
            }

            if (_user) {
                sendSms(_user.password, loginPhone);
                return;
            } else {
                _callback(lz.Config.errors.getError(lz.Config.errors.LOGIN_USER_NOT_FOUND));
                return;
            }
        });
    } else {
        _callback(lz.Config.errors.getError(lz.Config.errors.REQUEST_ERROR), _opts.user);
        return;
    }

    function sendMail(_email, _password) {
        // create reusable transporter object using SMTP transport
        var transporter = nodemailer.createTransport({
            service: 'Gmail',
            auth: {
                user: 'oneminute3b@gmail.com',
                pass: '690854LR'
            }
        });

        // NB! No need to recreate the transporter object. You can use
        // the same transporter object for all e-mails

        // setup e-mail data with unicode symbols
        var mailOptions = {
            from: 'oneminute3b@gmail.com', // sender address
            to: _email, // list of receivers
            subject: '找回密码', // Subject line
            text: '用户您好。您的密码为: ' + _password // plaintext body
        };

        // send mail with defined transport object
        transporter.sendMail(mailOptions, function (_err, _info) {
            if (_err) {
                lz.Logger.error(_err);
                _callback(lz.Config.errors.getError(lz.Config.errors.SEND_EMAIL_ERROR));
            } else {
                lz.Logger.debug('/findpassword: sendMail: 邮件发送完毕: ' + _info.response);
                _callback(null, _opts.user);
            }
        });
    };

    function sendSms(_password, _phone) {
        var content = util.format(lz.Config.sms.templates.findpassword, _password);
        var url = util.format(lz.Config.sms.url, lz.Config.sms.account, lz.Config.sms.password, _phone, content);
        lz.Logger.debug("/findpassword: 准备发送密码。", url);
        request(url, function (_err, _res, _body) {
            /*
             <?xml version="1.0" encoding="utf-8"?>
             <SubmitResult xmlns="http://106.ihuyi.cn/">
             <code>2</code>
             <msg>提交成功</msg>
             <smsid>24226341</smsid>
             </SubmitResult>
             */
            if (!_err && _res.statusCode == 200) {
                var result = xmlParser.toJson(_body, {object: true}).SubmitResult;
                lz.Logger.debug("/findpassword: 收到短信平台的反馈信息: ", result);
                if (result.code == 2) {
                    _callback(null, _opts.user);
                } else {
                    lz.Logger.error("/findpassword: 发送短信出现错误。", _err);
                    _callback(lz.Config.errors.getError(lz.Config.errors.REQUEST_SMS_ERROR, {msg: result.msg}));
                }
            } else {
                lz.Logger.error("/findpassword: 发送短信出现错误。", _err);
                _callback(lz.Config.errors.getError(lz.Config.errors.REQUEST_SMS_ERROR, _err));
            }
        });
    }
};
